package com.zf.yichat.service.impl;

import com.zf.yichat.dto.UserInviteSearchDto;
import com.zf.yichat.mapper.UserInviteMapper;
import com.zf.yichat.mapper.UserMapper;
import com.zf.yichat.model.User;
import com.zf.yichat.model.UserInvite;
import com.zf.yichat.service.BalanceService;
import com.zf.yichat.service.PushService;
import com.zf.yichat.service.SysDictService;
import com.zf.yichat.service.UserInviteService;
import com.zf.yichat.service.UserService;
import com.zf.yichat.utils.YiChatMsgCode;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import com.zf.yichat.vo.BalanceType;
import com.zf.yichat.vo.DictKey;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.internal.util.Contracts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import javax.annotation.Resource;

import tk.mybatis.mapper.entity.Example;

/**
 * @date Created in 2020/10/13 16:14
 * @description
 */
@Service
public class UserInviteServiceImpl implements UserInviteService {
    @Autowired
    PushService pushService;

    @Autowired
    UserService userService;

    @Resource
    UserInviteMapper userInviteMapper;

    @Autowired
    BalanceService balanceService;

    @Autowired
    SysDictService sysDictService;
    @Autowired
    private UserMapper userMapper;
    @Override
    public FsResponse addDetail(Long userId, Long referId) {
        UserInvite userInvite = selectByUserId(userId);
     //   Contracts.assertTrue(Objects.isNull(userInvite), "用户已绑定邀请码");

//        //查找我的下级
//        Example example=new Example(User.class);
//        example.createCriteria().andEqualTo("ucode",ucode);
//
//        List<User> userCheck=userMapper.selectByExample(example);
//        if(userCheck!=null&&userCheck.size()!=0){
//            ucode=createShareCode();
//        }
//        //查看我的邀请人是否为我的下级
//        if (StringUtils.isNotEmpty(ids) && ids.contains(String.valueOf(referId))) {
//
//        }

//        BigDecimal money = new BigDecimal(sysDictService.selectOne(DictKey.user_invite).getValue());

        userInvite = new UserInvite();
        userInvite.setStatus(0);
        userInvite.setReferId(referId);
        userInvite.setUserId(userId);
    //    userInvite.setMoney(money);
        userInviteMapper.insertSelective(userInvite);

        //        return FsResponseGen.successData(selectInviteUser(userId));
        return FsResponseGen.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void effectDetail(Long userId, String idNumber, String realName) {
        UserInvite userInvite = selectByUserId(userId);
        if (Objects.nonNull(userInvite) && userInvite.getStatus() == 0) {
            userInvite.setStatus(1);
            userInviteMapper.updateByPrimaryKeySelective(userInvite);

            User user = userService.selectById(userId);
            //更新推荐人余额
            balanceService.update(userInvite.getReferId(), BalanceType.USER_INVITE, userInvite.getMoney(), userId, "邀请用户奖励");
            pushService.sendSingle(userInvite.getReferId(), "奖励到账通知", "您邀请的用户\"" + user.getNick() + "\"完成实名认证，已为您发放" + userInvite.getMoney() + "元现金奖励", true);
        }
    }

    private UserInvite selectByUserId(Long userId) {
        Example example = new Example(UserInvite.class);
        example.createCriteria().andEqualTo("userId", userId);
        return userInviteMapper.selectOneByExample(example);
    }

    @Override
    public User selectInviteUser(Long userId) {
        UserInvite userInvite = selectByUserId(userId);
        if (Objects.isNull(userInvite)) {
            return null;
        }
        return userService.selectById(userInvite.getReferId());
    }

    @Override
    public List<List<UserInviteSearchDto>> selectInviteList(Long userId, Integer startLevel, Integer endLevel) {
        //        PageHelper.startPage(page.getPageNo(), page.getPageSize());
        //        _15001581,15001577_15001614,15001944
        String ids = userInviteMapper.selectChildrenIds(userId, startLevel, endLevel);
        List<List<UserInviteSearchDto>> userInviteLists = new ArrayList<>();
        if (StringUtils.isNotEmpty(ids)) {
            String[] levelIds = ids.split("_");
            //第一个_是空字符串
            for (int i = 1; i < levelIds.length; i++) {
                List<UserInviteSearchDto> userInviteSearchDtos = userInviteMapper.selectUserInviteListByIds(Arrays.asList(levelIds[i].split(",")));
                userInviteSearchDtos.forEach(v -> v.setMoney(userInviteMapper.countUserInviteMoney(userId, v.getId(), BalanceType.PACKET_FANLI_INVITE_GET.getVal())));

                userInviteLists.add(userInviteSearchDtos);
            }
        }
        return userInviteLists;
    }

    @Override
    public Integer countInviteLevels(Long userId) {
        Integer levels = 0;
        String ids = userInviteMapper.selectChildrenIds(userId, null, null);
        if (StringUtils.isNotEmpty(ids)) {
            levels = ids.split("_").length - 1;
        }
        return levels;
    }
}
